<?php
	class OrdersController extends PaidListingsAppController
	{
		var $name = "Orders";
		function admin_index()
		{
            $this->Order->ListingPlan->showUserInfo();
            App::import("Vendor","Searchable.GigaSearch");
            $Search = new GigaSearch($this->Order);
            $fields = $this->Order->getFields('group','search');
            $this->paginate['conditions'] = array();
            if($this->data)
            {
              $url = $Search->toUrlArray($this->data['Order']);
              $this->redirect($url);
            }
            $this->data['Order'] = $Search->toDataFromUrl($fields, $this->params['named']);
            if($this->data['Order'])
            {
              $data = $this->data['Order'];
              if(isset($data['listing_plan_status']))
              {
                $this->paginate['conditions']['ListingPlan.status'] = $data['listing_plan_status'];
                unset($data['listing_plan_status']);
              }
              $conditions = $Search->createConditions($fields,$data);
              $this->paginate['conditions']  = am($this->paginate['conditions'],$conditions);
            }
            $this->paginate['order'] = "Order.id  DESC";
            $this->paginate['recursive'] = 0;
			$orders = $this->paginate();
			$listingIds = Set::extract($orders,'{n}.ListingPlan.listing_id');
			$listings = cri("Listing")->find("list",array('recursive'=>-1,"conditions"=>array("id"=>$listingIds),'fields'=>array('id','title')));
			
            //$listings = Set::combine($listings,'{n}.Listing.id','{n}');
			$this->set("listings",$listings);
			$this->set("orders",$orders);
            $this->helpers[] = "Index";
            $this->helpers[] = "Searchable.SearchForm";
            $plans = cri("PaidListings.Plan")->find("list");
            $this->Order->setFieldProperties("plan_id",array("options"=>$plans));
		}
		
		function admin_view($orderId)
		{
            $this->Order->ListingPlan->showUserInfo();
			$this->Order->recursive = 0;
			$order = $this->Order->findById($orderId);
			$transactions = $this->Order->Transaction->find("all",array("conditions"=>array("order_id"=>$orderId),'recursive'=>-1));
			$listingTitle = cri("Listing")->field('title',array("id"=>$order['ListingPlan']['listing_id']));
			$this->set("listingTitle",$listingTitle);
			$this->set("order",$order);
			$this->set("transactions",$transactions);
		}
		function admin_edit($orderId)
		{
			$this->Order->recursive = 0;
			$order = $this->Order->findById($orderId);
			if($this->data)
			{
                $activated = false;
				if(($order['Order']['status'] != Order::STATUS_COMPLETED) && (@$this->data['Order']['payment_completed'] || $this->data['Order']['status'] == Order::STATUS_COMPLETED || ($order['ListingPlan']['status'] == ListingPlan::STATUS_INACTIVE && $this->data['Order']['listing_plan_status'] == ListingPlan::STATUS_ACTIVE)))
				{
                    $activated = true;
					$Offline = cri("PaidListings.PaymentHandler")->getPaymentHandlerObject("Offline");
					$this->Order->setAsCompleted($orderId);
					$this->Order->Transaction->createTransaction($Offline,$order,Transaction::SUCCESSFUL,array());
				}else if($order['Order']['status'] != $this->data['Order']['status'])
				{
					$this->id = $orderId;
					$this->Order->saveField('status',$this->data['Order']['status']);
				}
				if($order['Order']['payment_type']!= Plan::PAYMENT_TRIAL && $activated == false)
				{
					$endDate = null;
					if(!@$this->data['Order']['never_expire'])
					{
						$endDate = @$this->data['Order']['end_date'];
					}
                    if($order['Order']['payment_type'] != Plan::PAYMENT_SUBSCRIPTION || $endDate)
                    {
                        $this->Order->id = $orderId;
                        $this->Order->saveField('end_date',$endDate);
                    }
                                            
				}
				$adminNote = "";
				if($this->data['Order']['admin_note'])
				{
					$adminNote = $this->data['Order']['admin_note'];
				}
				$this->Order->id = $orderId;
				$this->Order->saveField('admin_note',$adminNote);
				if($order['ListingPlan']['status'] != $this->data['Order']['listing_plan_status'])
				{
					$this->Order->id = $orderId;
					$this->Order->ListingPlan->id = $order['ListingPlan']['id'];
					$this->Order->ListingPlan->saveField('status',$this->data['Order']['listing_plan_status']);
				}
				$plan = $order['ListingPlan']['plan_info']['Plan'];
				$plan = am($plan,$this->data['Plan']);
				$this->Order->ListingPlan->id = $order['ListingPlan']['id'];
				if(isset($plan['custom_fields']['fields']) && !is_array($plan['custom_fields']['fields']) )
				{
					$plan['custom_fields']['fields'] = explode(",",$plan['custom_fields']['fields']);
				}
				if(isset($plan['custom_fields']['fieldsets']) && !is_array($plan['custom_fields']['fieldsets']) )
				{
					$plan['custom_fields']['fieldsets'] = explode(",",$plan['custom_fields']['fieldsets']);
				}
				$this->Order->ListingPlan->saveField('plan_info',array("Plan"=>$plan));
				$this->Order->reImplement($orderId);
				$this->successMsg(__("Order has been changed"));
				$this->redirect(array("action"=>"view",$orderId));
			}else
			{
				$this->data = $order;
				$this->data['Plan'] = $order['ListingPlan']['plan_info']['Plan'];
			}
			$listCategoryIds = cri("Listing")->field("category_list",array("id"=>$order['ListingPlan']['listing_id']));
			$this->set("listCategoryIds",$listCategoryIds);
			$this->set("order",$order);
		}

		function admin_dashboard($ajax = false)
		{
			if($ajax)
			{
				$this->layout = false;
			}
            $this->pageTitle = __("Revenue Report");
			$endDate = date("Y-m-d");
			$startDate = date("Y-m-d",strtotime("-15 days"));	
			if(isset($_GET['start_date']))
			{
				$startDate = $_GET['start_date'];
			}
			if(isset($_GET['end_date']))
			{
				$endDate = $_GET['end_date'];
			}
			$this->data['Order'] = array('start_date'=>$startDate,'end_date'=>$endDate);
			$revenue = $this->Order->Transaction->find("all",array("recursive"=>-1,'conditions'=>array('status'=>Transaction::SUCCESSFUL,'amount > 0','date(created) <='=>$endDate,'date(created) >='=>$startDate),'fields'=>array("ROUND(sum(amount),2) as amount",'date(created) as date','id'),'group'=>"date(created)",'order'=>"date asc"));
			$plansSold = $this->Order->find("all",array('recursive'=>-1,'conditions'=>array('date(created) <='=>$endDate,'date(created) >='=>$startDate,'status'=>Order::STATUS_COMPLETED,'payment_type <>'=>Plan::PAYMENT_TRIAL),'fields'=>array('count(id) as count','date(created) as date','id'),'group'=>"date(created)",'order'=>"date asc"));
			$this->set(compact('revenue','plansSold','endDate','startDate'));
		}
		
		function process()
		{
			if(!$this->data)
			{
				$this->data = array();
			}
			$orderId = $this->data['Order']['id'];
			$this->Order->recursive = 0;
			$order = $this->Order->findById($orderId);
			if(!$order)
			{
				$this->errorMsg(__("Invalid Order Id"));
				$this->redirect("/");
			}
			if($this->Session->read("Auth.User.id") != $order['ListingPlan']['user_id'])
			{
				$this->errorMsg(__("Invalid Order Id"));
				$this->redirect('/');				
			}
			if($this->data)
			{
				$paymentGateway = null;
				if(isset($this->data["Order"]['payment_gateway']))
				{
					$paymentGateway = $this->data["Order"]['payment_gateway'];
				}
				$paymentGateways = cri("PaidListings.PaymentHandler")->getPaymentHandlers();
				$invalidGateway  = true;
				if($paymentGateway && isset($paymentGateways[$paymentGateway]) && $paymentGateways[$paymentGateway]->isEnabled())
				{
					
					$invalidGateway = false;
					if($order['Order']['payment_type'] == Plan::PAYMENT_SUBSCRIPTION && $paymentGateways[$paymentGateway]->useForSubscription() == false)
					{
						$invalidGateway = true;
					}
				}
				if($invalidGateway === false)
				{
					$paymentGatewayObject = $paymentGateways[$paymentGateway];
					$paymentGatewayObject->process($this,$orderId);
				}else
				{
					$this->errorMsg(__("Please select a valid payment gateway."));
					$this->redirect(array("action"=>"invoice",$orderId));
				}
			}
		}
		function invoice($orderId)
		{
			$this->Order->recursive = 0;
			$order = $this->Order->findById($orderId);
			$listingId = $order['ListingPlan']['listing_id'];
			$ListingModel = cri("Listing");
			$ListingModel->recursive = -1;
			$listing = $ListingModel->findById($listingId);
			if($this->Session->read("Auth.User.id") != $order['ListingPlan']['user_id'])
			{
				$this->redirect('/');				
			}
			$this->pageTitle = sprintf(__("Invoice for %s"),$listing['Listing']['title']);
			$this->set("listing",$listing);
			$this->set("order",$order);
		}
		
		function my()
		{
			$ListingModel = cri("Listing");
			$ListingModel->recursive = -1;
			$userId = $this->Session->read("Auth.User.id");
			$this->Order->recursive = 0;
			$this->paginate['conditions'] = array("ListingPlan.user_id"=>$userId);
			$this->paginate['order'] = "Order.created DESC";
			$orders = $this->paginate();
			$this->helpers[] = "Index";
            $listingIds = Set::extract($orders,"{n}.ListingPlan.listing_id");
            $listings = array();
            if($listingIds)
            {
              $ListingModel->recursive = -1;
              $listings = $ListingModel->find("all",array("conditions"=>array("Listing.id"=>$listingIds)));
              $listings = Set::combine($listings,'{n}.Listing.id','{n}');  
            }
            $this->set("listings",$listings);
			$this->set("orders",$orders);
		}
	}
?>
